package com.ducanh.doan.ui.screen;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

public abstract class BaseFragment extends Fragment {
	
	protected static final String PREV_FRAGMENT_TAG = "previous_fragment_tag";
	
	public abstract int getLayoutId();
	
	public abstract int getContainerId();
	
	public void startFragment(BaseFragment fragment) {
		fragment.setPrevTag(getFragmentTag());
		FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
		ft.detach(this);
		ft.add(fragment.getContainerId(), fragment, fragment.getFragmentTag());
		ft.commit();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		loadResource();
	}

	public String getFragmentTag() {
		return getClass().getSimpleName() + hashCode();
	}
	
	public void setPrevTag(String tag) {
		Bundle args = getArguments();
		if (args == null)
			args = new Bundle();
		args.putString(PREV_FRAGMENT_TAG, tag);
		setArguments(args);
	}
	
	public String getPrevTag() {
		if (getArguments() != null) {
			String tag = getArguments().getString(PREV_FRAGMENT_TAG);
			return tag;
		}
		return null;
	}
	
	public Fragment getPreviousFragment() {
		if (getPrevTag() != null) {
			Fragment f = getActivity().getSupportFragmentManager().findFragmentByTag(getPrevTag());
			if (f != null) {
				return f;
			}
		}
		return null;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if (getActivity() instanceof FragmentCallBack) {
			((FragmentCallBack) getActivity()).setCurrentFragment(this);
		}
	}
	
	public void reload() {
		FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
		ft.detach(this);
		ft.attach(this);
		ft.commit();
	}
	
	public abstract void loadResource();
	

	public void onBackPressed() {
		Fragment f = getPreviousFragment();
		if (f != null) {
			FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
			ft.remove(this);
			ft.attach(f);
			ft.commit();
		} else {
			if (getActivity() instanceof FragmentCallBack)
				((FragmentCallBack) getActivity()).onActivityOnBack();
		}
	}
	
	public interface FragmentCallBack {
		
		public void onActivityOnBack();
		
		public void setCurrentFragment(BaseFragment f);
	}
}
